package com.dmy.controller;

import com.dmy.common.utils.qr_code.QRCodeConfig;
import com.dmy.common.utils.qr_code.QRCodeHelper;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.zxing.WriterException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.nio.ch.IOUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * create by huahuadelei for 2020/1/5
 */
@RestController
@RequestMapping("/coder")
public class CoderController {

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private QRCodeHelper qrCodeHelper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/qr")
    public void generationQrCode(String content, HttpServletResponse response) throws IOException, WriterException {
        response.setHeader("Content-Type","image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        qrCodeHelper.generateQrCodeToStream(content,new QRCodeConfig(),outputStream);
    }

    @GetMapping("/vc")
    public void generationVcCode(HttpSession session,HttpServletResponse response) throws IOException, WriterException {
        response.setHeader("Content-Type","image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        ImageIO.write(image,"png",outputStream);
        redisTemplate.boundValueOps("KAPTCHAPRODUCER_VILDCODE:"+session.getId()).set(text,300, TimeUnit.SECONDS );
    }
}
